import 'package:aero_frisbee/app/model/af_coin_create_model/af_coin_create_model.dart';
import 'package:aero_frisbee/app/model/af_coin_product_model/af_coin_product_model.dart';
import 'package:aero_frisbee/app/req/af_req_api.dart';
import 'package:aero_frisbee/core/state/view_state.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:tuple/tuple.dart';

part 'af_app_purchase_view_model.g.dart';

@riverpod
FutureOr<List<AfCoinProductModel>> getAfCoinProductFuture(
    GetAfCoinProductFutureRef ref) {
  final api = ref.watch(appApiProvider);
  return api.getAfCoinProductList();
}

@riverpod
class GetPurchaseDetailsService extends _$GetPurchaseDetailsService {
  @override
  ViewState<Tuple3<AfCoinCreateModel, List<ProductDetails>, int>> build() {
    return const ViewState.idle();
  }

  getPurchaseDetails(
      {required Set<String> kIds, required int exchangeCoin}) async {
    state = const ViewState.loading();
    try {
      final api = ref.watch(appApiProvider);
      final order = await api.coinCreateOrder(goodsCode: kIds.first);
      final response = await InAppPurchase.instance.queryProductDetails(kIds);
      state =
          ViewState.ready(Tuple3(order, response.productDetails, exchangeCoin));
    } catch (e) {
      state = ViewState.error(error: e.toString());
    }
  }
}

@riverpod
class VerifyPurchaseService extends _$VerifyPurchaseService {
  @override
  ViewState<bool> build() {
    return const ViewState.idle();
  }

  verifyPurchase({
    required AfCoinCreateModel item,
    required PurchaseDetails purchaseDetails,
  }) async {
    final api = ref.watch(appApiProvider);
    state = const ViewState.loading();
    try {
      await api.verifyPurchase(
        orderNo: item.orderNo ?? '',
        payload: purchaseDetails.verificationData.serverVerificationData,
        transactionId: purchaseDetails.purchaseID ?? '',
      );

      state = const ViewState.ready(true);
    } catch (e) {
      state = ViewState.error(error: e.toString());
    }
  }
}
